import React, { useState, useEffect, FC, forwardRef, useImperativeHandle } from 'react'
import { Col, Row, Table, Modal, } from 'antd'
import { Scrollbars } from 'react-custom-scrollbars'
import XlModalFC from '@/components/xlmodal/xlmodal'
import XlButtonFC from '@/components/xlbutton/xlbutton'
import { DownOutlinedIcon } from '@/models/icons'
import type { ColumnsType } from 'antd/es/table'
import { IData, PagingSize, IKnowLedgeBaseFileListModel, IResponseCodeType } from '@/models/common'
import util from '@/utils/util'
import * as api from '@/api'
import './documentlistmodal.scss'

interface ColumnsDataType {
  [name: string]: string
}

export interface IDocumentListRef {
  getDocumentList: (base_id: string) => void
}
export interface IDocumentListXlModalProps {
  onCancel?: () => void
  onOk?: () => void
  ref?: React.ForwardedRef<IDocumentListRef>
}

export interface IViewModel {
  pageLoading: boolean
  /**
   * 表格数据
   */
  documnetTableList: ColumnsDataType[]
  /**
   * 当前页码
   */
  page: number
  /**
   * 每页数量
   */
  pageSize: number
  /**
   * 是否还有下一页
   */
  hasNextPage: boolean
  documentListModalOpen: boolean
  base_id: string
}

const DocumentListXlModal: FC<IDocumentListXlModalProps> = forwardRef((props, ref) => {
  const [data, setData] = useState<IData<IViewModel>>({
    ViewModel: {
      pageLoading: false,
      documentListModalOpen: false,
      documnetTableList: [],
      page: 1,
      pageSize: PagingSize.PageSize,
      hasNextPage: false,
      base_id: ''
    }
  })

  useImperativeHandle(ref, () => ({
    getDocumentList: (base_id: string) => {
      events.initDocumentList(base_id)
    },
  }))

  const events = {
    initDocumentList(base_id: string) {
      const { ViewModel } = data
      ViewModel.base_id = base_id
      ViewModel.documnetTableList = []
      ViewModel.page = 1
      ViewModel.hasNextPage = false
      ViewModel.pageLoading = true
      ViewModel.documentListModalOpen = true
      setData({ ...data })
      methods.requestDocumentList()
    },
    onClickDeleteRow(_: ColumnsDataType, record: ColumnsDataType, index: number) {
      Modal.confirm({
        title: '删除',
        centered: true,
        closable: true,
        content: '确认删除吗？',
        onOk() {
          return new Promise(async (resolve, reject) => {
            await methods.requestDeleteDocumentList(record.file_id)
            resolve(null)
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel() {

        },
      })
    },
    onClickLoadMore() {
      const { ViewModel } = data
      if (ViewModel.hasNextPage) {
        ViewModel.page = ViewModel.page + 1
        ViewModel.pageLoading = true
        setData({ ...data })
        methods.requestDocumentList()
      }
    },
    onDocumentListXlModalOk() {
      const { ViewModel } = data
      ViewModel.documentListModalOpen = false
      setData({ ...data })
    },
    onDocumentListXlModalCancel() {
      const { ViewModel } = data
      ViewModel.documentListModalOpen = false
      setData({ ...data })
    },
  }

  const methods = {
    async requestDocumentList() {
      const { ViewModel } = data
      let { documnetTableList } = ViewModel
      let res = await api.common.getFileListByBaseId<IKnowLedgeBaseFileListModel>({
        base_id: ViewModel.base_id,
        page: ViewModel.page,
        limit: ViewModel.pageSize
      })
      const { code, data: documentListData, message } = res
      if (code == IResponseCodeType.Success) {
        if (ViewModel.page == 1) {
          documnetTableList = []
        }
        let { file_list } = documentListData
        ViewModel.documnetTableList = [...documnetTableList, ...file_list]
        if (file_list.length < ViewModel.pageSize) {
          ViewModel.hasNextPage = false
        } else {
          ViewModel.hasNextPage = true
        }
      } else {
        util.alertTip(message)
      }
      ViewModel.pageLoading = false
      setData({ ...data })
    },
    async requestDeleteDocumentList(file_id: React.Key) {
      const { ViewModel } = data
      let res = await api.common.deleteFileFromKnowLedgeBase<null>({
        base_id: ViewModel.base_id,
        file_id
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        events.initDocumentList(ViewModel.base_id)
      } else {
        util.alertTip(message)
      }
    },
    createColumns() {
      const columns: ColumnsType<ColumnsDataType> = [
        {
          title: '文档名称',
          align: "left",
          key: 'file_fullname',
          dataIndex: 'file_fullname',
        },
        {
          title: '文件大小',
          align: "left",
          key: 'file_size',
          dataIndex: 'file_size',
        },
        {
          title: '创建日期',
          align: "left",
          key: 'create_at',
          dataIndex: 'create_at',
        },
        {
          title: '操作',
          align: "center",
          width: 100,
          dataIndex: "action",
          key: 'action',
          render: (_, record: any, index) => (
            <XlButtonFC type='primary' size='small' onClick={() => events.onClickDeleteRow(_, record, index)}>
              删除
            </XlButtonFC>
          ),
        }
      ]
      return columns
    },
    renderPage() {
      return (
        <XlModalFC
          title="文件清单"
          open={data.ViewModel.documentListModalOpen}
          onOk={events.onDocumentListXlModalOk}
          onCancel={events.onDocumentListXlModalCancel}
          cancelText="取消"
          okText="确定"
          className='knowledgebaseadmin-documentlist-modal'
          width={1000}
          footer={null}
        >
          <Col className='documentlist-wrap'>
            {/* 按钮操作区域 */}
            <Row align='middle' justify='space-between' className='buttonGroupWrap' gutter={[0, 10]}>
              <Col>

              </Col>
              <Col className='count'>
                {data.ViewModel.hasNextPage ? '已部分加载' : '已全部加载'}，共{data.ViewModel.documnetTableList.length}个
              </Col>
            </Row>
            {/* 表格区域 */}
            <Col className='tableWrap'>
              <Col className='tableContent'>
                <Table
                  scroll={{
                    x: '100%',
                    y: 400
                  }}
                  loading={data.ViewModel.pageLoading}
                  tableLayout='fixed'
                  bordered
                  rowKey='file_id'
                  pagination={false}
                  columns={methods.createColumns()}
                  dataSource={data.ViewModel.documnetTableList}
                />
              </Col>

              {
                data.ViewModel.hasNextPage ? <Row className='loadmore-wrap' align='middle' justify='center' onClick={events.onClickLoadMore}>
                  <Col>点击加载更多</Col>
                  <Row><DownOutlinedIcon className='loadmore-icon' /></Row>
                </Row> : null
              }
            </Col>
          </Col>
        </XlModalFC>
      )
    }
  }

  return methods.renderPage()

})

export default DocumentListXlModal
